#!/usr/bin/env bash
set -e

export  GOPROXY=https://proxy.golang.com.cn,direct


help() {
    echo "使用方式:"
    echo "  build.sh [-s app_name] [-v version] [-g go_bin]"
    echo "参数详解:"
    echo "  app_name 需要编译的应用名称,选项: proxy,player,recorder,video,screenshot.默认是所有应用,多个应用可以逗号分割"
    echo "  version 编译后的文件版本号,默认为当前git的commit id"
    echo "  go_bin 使用的golang程序"
    exit
}

getOutFile(){
  build_name=$1
  output_dir=$2
  output_file="${output_dir}"/${build_name}
}



while getopts 's:v:g:h' OPT; do
    case $OPT in
        s) app_names="$OPTARG";;
        v) build_version="$OPTARG";;
        g) goBin="$OPTARG";;
        h) help;;
        ?) help;;
    esac
done


## 获取当前环境
## shellcheck disable=SC2046
cd $(dirname "$0")/ || exit 1;


# 如果go bin 不存在，则去环境变量中查找
if [ ! -x "$goBin" ]; then
    goBin=$(which go)
fi
if [ ! -x "$goBin" ]; then
    echo "No goBin found."
    exit 2
fi


# 编译时间
build_date=$(date +"%Y-%m-%d %H:%M:%S")
# 编译时候当前git的commit id
build_git=$(git rev-parse --short HEAD)
# 编译的golang版本
go_version=$(${goBin} version)
#编译版本
if [ -z "$build_version" ]; then
    build_version="$build_git"
fi

if [ -z "$app_names" ]; then
    app_names="proxy,player,recorder,video,screenshot"
fi


echo "start to build project $app_names" "$build_date"
# shellcheck disable=SC2154
echo "$go_version"
pwd
root_dir="$(pwd)"

ldflags=()

# 链接时设置变量值
ldflags+=("-X" "\"main.BuildVersion=${build_version}\"")
ldflags+=("-X" "\"github.com/osgochina/dmicro/easyservice.BuildVersion=${build_version}\"")
ldflags+=("-X" "\"github.com/osgochina/dmicro/easyservice.BuildGoVersion=${go_version}\"")
ldflags+=("-X" "\"github.com/osgochina/dmicro/easyservice.BuildGitCommitId=${build_git}\"")
ldflags+=("-X" "\"github.com/osgochina/dmicro/easyservice.BuildTime=${build_date}\"")


for app_name in $(echo $app_names | sed "s/,/ /g")
do
  getOutFile $app_name "$root_dir/bin"
  cd "$root_dir/cmd/$app_name/"
  echo "进入[$(pwd)]目录"
  ${goBin} build -v -ldflags "${ldflags[*]}"  -o "${output_file}"  || exit 1
  echo "build $app_name done."
done